<script setup>
import { ref } from 'vue'
import LetterContentInput from './LetterContentInput.vue'
import ZlcodeButton from '@/components/zlcode/button/ZlButton.vue'
import SendSvg from '@/views/components/svg/SendSvg.vue'
import DraftsSvg from '@/views/components/svg/DraftsSvg.vue'
import { Hide, View } from '@element-plus/icons-vue'
import { aesEncrypt } from '@/utils/crypto'
import { letterSendService, letterSaveService } from '@/api/letter'
import { ZlMessage } from '@/utils/message'
import LoadingCar from './LoadingCar.vue'
import LoadingLetter from './LoadingLetter.vue'
import { userIsLogin } from '@/api/user'
import { useRouter } from 'vue-router'
import { watch } from 'vue'
import emitter from '@/utils/event'

const router = useRouter()

const loading = ref(false)
const loadingLetterRef = ref(false)

// 定义props
const props = defineProps({
  message: {
    required: false
  }
})

const currentDate = new Date()
// 获取年份、月份和日期
const year = currentDate.getFullYear()
const month = String(currentDate.getMonth() + 1) // 月份从0开始，所以需要+1，并且用padStart确保是两位数
const day = String(currentDate.getDate()) // 用padStart确保是两位数
const resultDate = `${year}年${month}月${day}日`
const data = ref({
  title: '一封来自' + resultDate + '的信',
  tempTitle: '一封来自' + resultDate + '的信',
  content: '',
  sendTime: '',
  isPublic: false,
  toEmail: '',
  isAgree: false
})

// 定义禁用日期的函数
const disabledDate = (time) => {
  const now = new Date()
  const sevenDaysLater = new Date(now)
  sevenDaysLater.setDate(now.getDate() + 7)
  return time.getTime() < sevenDaysLater.getTime()
}

// 弹框
const centerDialogVisible = ref(false)
const option = ref('')
const openDialog = (choice) => {
  if (choice == 'send') {
    // 校验数据
    const content = inputContent.value.getHtmlContent()
    if (data.value.tempTitle == null || data.value.tempTitle.length <= 0) {
      ZlMessage.error('请输入标题')
      return
    }
    if (data.value.tempTitle == null || data.value.tempTitle.length >= 20) {
      ZlMessage.error('标题长度最多为20字符哦!')
      return
    }
    if (content.length > 10000) {
      ZlMessage.error('请少写点内容，服务器顶不住啦！')
      return
    }
    if (data.value.sendTime == null || data.value.sendTime.length <= 0) {
      ZlMessage.error('请选择寄信时间！')
      return
    }
    if (data.value.toEmail == null || data.value.toEmail == '') {
      ZlMessage.error('请输入邮箱')
      return
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(data.value.toEmail)) {
      ZlMessage.error('请输入合法邮箱!')
      return
    }
    option.value = '发送'
  } else {
    option.value = '暂存'
  }
  centerDialogVisible.value = true
}
const inputContent = ref(null)
const push = async () => {
  // 判断用户是否登录
  const r = await userIsLogin()
  if (r.data.data == false) {
    ZlMessage.error(
      '先去主页面登录后, 刷新此页面, 即可发送信件哦! (记得复制好信件内容哦)'
    )
    return
  }
  // 1. 封装数据
  data.value.isAgree = true
  data.value.content = inputContent.value.getHtmlContent()

  // 2. 加密数据
  data.value.content = aesEncrypt(data.value.content)
  data.value.title = aesEncrypt(data.value.tempTitle)
  if (option.value == '发送') {
    // 请求发送定时信息
    centerDialogVisible.value = false
    loading.value = true
    const res = await letterSendService(data.value)
    if (res.data.code != 201) {
      // 跳转到定时发送成功页面
      router.push('/letter/sendok')
    }
    loading.value = false
  } else if (option.value == '暂存') {
    // 请求暂存信件
    centerDialogVisible.value = false
    loadingLetterRef.value = true
    const res = await letterSaveService(data.value)
    if (res.data.code != 201) {
      router.push('/letter/saveok')
    }
    loadingLetterRef.value = false
  } else {
    centerDialogVisible.value = false
  }
}

// ok！
watch(
  () => props.message,
  (newValue, oldValue) => {
    data.value.title = newValue.title
    data.value.tempTitle = newValue.title
    data.value.content = newValue.content
    data.value.isPublic = newValue.isPublic
    data.value.toEmail = newValue.toEmail
    data.value.sendTime = newValue.orgSendTime
    // 如果是修改，需要新增提交的请求data字段
    data.value.id = newValue.id
    emitter.emit('letter-set-content', newValue.content)
  }
)
</script>

<template>
  <loading-car :loading="loading"></loading-car>
  <loading-letter :loading="loadingLetterRef"></loading-letter>

  <el-dialog
    v-model="centerDialogVisible"
    title="注意！"
    width="500"
    align-center
    :close-on-press-escape="false"
    :close-on-click-modal="false"
  >
    <div style="display: flex; align-items: center">
      <span>{{ option }}定时信件时表示您已同意：</span>
      <el-link
        href="/letter/docs"
        target="_blank"
        :underline="false"
        style="color: #42b983"
        >服务条款
      </el-link>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="push()"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>

  <div class="box">
    <div class="content">
      <null-box size="30"></null-box>

      <!-- 信件标题 -->
      <input type="text" v-model="data.tempTitle" placeholder="信件标题" />

      <null-box size="20"></null-box>

      <letter-content-input ref="inputContent"></letter-content-input>

      <null-box size="30"></null-box>

      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <!-- 寄出时间 -->
        <div class="time">
          <div class="min-title">寄出时间</div>
          <el-date-picker
            v-model="data.sendTime"
            type="datetime"
            placeholder="date and time"
            :disabled-date="disabledDate"
            :show-now="false"
          />
        </div>

        <!-- 是否公开 -->
        <div class="public">
          <div class="group">
            <div>是否公开</div>
            <el-switch
              size="large"
              v-model="data.isPublic"
              :active-action-icon="View"
              :inactive-action-icon="Hide"
            />
          </div>
        </div>
      </div>

      <null-box size="30"></null-box>

      <!-- 寄往邮箱 -->
      <div class="min-title">寄往邮箱</div>
      <input
        class="send-email"
        type="text"
        v-model="data.toEmail"
        placeholder="✉ hello@xiaoazi.email.com"
        autocomplete="new-password"
      />

      <null-box size="30"></null-box>

      <div class="send-btn-box">
        <zlcode-button
          class="btn"
          bgc="#63b6fd"
          left-text="GO!"
          right-text="&nbsp; 投递 &nbsp;"
          brd-color="#DCDFE6"
          @click="openDialog('send')"
        >
          <template #svg>
            <send-svg></send-svg>
          </template>
        </zlcode-button>
        <zlcode-button
          class="btn"
          bgc="#FFd449"
          left-text="ON!"
          right-text="&nbsp; 暂存 &nbsp;"
          brd-color="#DCDFE6"
          @click="openDialog()"
        >
          <template #svg>
            <drafts-svg></drafts-svg>
          </template>
        </zlcode-button>
      </div>
      <null-box size="25"> </null-box>
    </div>
  </div>
</template>
<style scoped>
::v-deep .date_picker .el-picker__footer .el-button--text {
  display: none;
}
.box {
  display: flex;
  justify-content: center;
}
.content {
  width: 50%;
}
input {
  width: 100%;
  line-height: 50px;
  font-size: 24px;
  outline: none;
  border: none;
  border-bottom: 1px solid rgba(0, 0, 0, 0.15);
  transition: all 0.3s;
}
input:focus {
  border-bottom: 1px solid rgb(83, 175, 253);
}
.min-title {
  font-size: 14px;
  color: #4e4c57;
  padding-bottom: 5px;
}

.send-email {
  line-height: 30px;
  font-size: 16px;
  color: #4e4c57;
}

.send-btn-box {
  display: flex;
  justify-content: center;
}

.send-btn-box .btn {
  padding: 0 30px;
  /* background-color: #84ccf3; */
}
</style>
